const globalFontFamily = {
    ExtraLight: 'SourceHanSansCN-ExtraLight, Microsoft YaHei, Arial;',
    Light: 'SourceHanSansCN-Light, Microsoft YaHei, Arial;',
    Normal: 'SourceHanSansCN-Normal, Microsoft YaHei, Arial;',
    Regular: 'SourceHanSansCN-Regular, Microsoft YaHei, Arial;',
    Medium: 'SourceHanSansCN-Medium, Microsoft YaHei, Arial;',
    Bold: 'SourceHanSansCN-Bold, Microsoft YaHei, Arial;',
    Heavy: 'SourceHanSansCN-Heavy, Microsoft YaHei, Arial;'
};
const globalFontFace = {
    ExtraLight: `@font-face {
        font-family: 'SourceHanSansCN-ExtraLight';
        src: url('images/SourceHanSansCN-ExtraLight.eot');
        src:
          url('images/SourceHanSansCN-ExtraLight.eot?#font-spider') format('embedded-opentype'),
          url('images/SourceHanSansCN-ExtraLight.woff') format('woff'),
          url('images/SourceHanSansCN-ExtraLight.ttf') format('truetype'),
          url('images/SourceHanSansCN-ExtraLight.svg') format('svg');
        font-weight: normal;
        font-style: normal;
      }`,
    Light: `@font-face {
        font-family: 'SourceHanSansCN-Light';
        src: url('images/SourceHanSansCN-Light.eot');
        src:
          url('images/SourceHanSansCN-Light.eot?#font-spider') format('embedded-opentype'),
          url('images/SourceHanSansCN-Light.woff') format('woff'),
          url('images/SourceHanSansCN-Light.ttf') format('truetype'),
          url('images/SourceHanSansCN-Light.svg') format('svg');
        font-weight: normal;
        font-style: normal;
      }`,
    Normal: `@font-face {
        font-family: 'SourceHanSansCN-Normal';
        src: url('images/SourceHanSansCN-Normal.eot');
        src:
          url('images/SourceHanSansCN-Normal.eot?#font-spider') format('embedded-opentype'),
          url('images/SourceHanSansCN-Normal.woff') format('woff'),
          url('images/SourceHanSansCN-Normal.ttf') format('truetype'),
          url('images/SourceHanSansCN-Normal.svg') format('svg');
        font-weight: normal;
        font-style: normal;
      }`,
    Regular: `@font-face {
        font-family: 'SourceHanSansCN-Regular';
        src: url('images/SourceHanSansCN-Regular.eot');
        src:
          url('images/SourceHanSansCN-Regular.eot?#font-spider') format('embedded-opentype'),
          url('images/SourceHanSansCN-Regular.woff') format('woff'),
          url('images/SourceHanSansCN-Regular.ttf') format('truetype'),
          url('images/SourceHanSansCN-Regular.svg') format('svg');
        font-weight: normal;
        font-style: normal;
      }`,
    Medium: `@font-face {
        font-family: 'SourceHanSansCN-Medium';
        src: url('images/SourceHanSansCN-Medium.eot');
        src:
          url('images/SourceHanSansCN-Medium.eot?#font-spider') format('embedded-opentype'),
          url('images/SourceHanSansCN-Medium.woff') format('woff'),
          url('images/SourceHanSansCN-Medium.ttf') format('truetype'),
          url('images/SourceHanSansCN-Medium.svg') format('svg');
        font-weight: normal;
        font-style: normal;
      }`,
    Bold: `@font-face {
        font-family: 'SourceHanSansCN-Bold';
        src: url('images/SourceHanSansCN-Bold.eot');
        src:
          url('images/SourceHanSansCN-Bold.eot?#font-spider') format('embedded-opentype'),
          url('images/SourceHanSansCN-Bold.woff') format('woff'),
          url('images/SourceHanSansCN-Bold.ttf') format('truetype'),
          url('images/SourceHanSansCN-Bold.svg') format('svg');
        font-weight: normal;
        font-style: normal;
      }`,
    Heavy: `@font-face {
        font-family: 'SourceHanSansCN-Heavy';
        src: url('images/SourceHanSansCN-Heavy.eot');
        src:
          url('images/SourceHanSansCN-Heavy.eot?#font-spider') format('embedded-opentype'),
          url('images/SourceHanSansCN-Heavy.woff') format('woff'),
          url('images/SourceHanSansCN-Heavy.ttf') format('truetype'),
          url('images/SourceHanSansCN-Heavy.svg') format('svg');
        font-weight: normal;
        font-style: normal;
      }`
};
const br = `<span style="font-family:Arial;"><br/></span>`;
const quickColor = ['000000','ffffff','333333','4c4c4c'];
const quickFontWeight = ['lighter','normal','bold','bolder'];
const keyCode = {
    up: 38,
    down: 40,
    left: 37,
    right: 39,
    a: 65,
    b: 66,
    c: 67,
    d: 68,
    e: 69,
    f: 70,
    g: 71,
    h: 72,
    i: 73,
    j: 74,
    k: 75,
    l: 76,
    m: 77,
    n: 78,
    o: 79,
    p: 80,
    q: 81,
    r: 82,
    s: 83,
    t: 84,
    u: 85,
    v: 86,
    w: 87,
    x: 88,
    y: 89,
    z: 90
};

Vue.component('v-style', {
    render: function (createElement) {
      return createElement('style', this.$slots.default)
    }
});

let vm = new Vue({
    el: '#productHelper',
    data() {
        return {
            mainOptions:{
                productName: 'aaa',
                imageExtension: 'jpg',
                UIWidth: 1920,
                pageNumber: 5,
                minWidth: 0,
                optionSubmit: false
            },
            globalColor: [],
            globalDarkTheme: true,
            globalLeftRight: true,
            presetPOptions:[
                {
                    id: 1,
                    fontSize: 50,
                    lineHeight: 60,
                    color: '000000',
                    fontWeight: 'normal',
                    letterSpacing: 0,
                    textAlign: 'left',
                    width: '100',
                    fontFamily: globalFontFamily.Regular,
                    content: '此处添加文字',
                    htmlContent: '此处添加文字',
                    position: {
                        top: 10,
                        left: 50
                    }
                },
                {
                    id: 2,
                    fontSize: 30,
                    lineHeight: 40,
                    color: '000000',
                    letterSpacing: 0,
                    fontWeight: 'normal',
                    textAlign: 'left',
                    width: '100',
                    fontFamily: globalFontFamily.Regular,
                    content: '此处添加文字',
                    htmlContent: '此处添加文字',
                    position: {
                        top: 10,
                        left: 50
                    }
                },
                {
                    id: 3,
                    fontSize: 20,
                    lineHeight: 30,
                    color: '000000',
                    letterSpacing: 0,
                    fontWeight: 'normal',
                    textAlign: 'left',
                    width: '100',
                    fontFamily: globalFontFamily.Regular,
                    content: '此处添加文字',
                    htmlContent: '此处添加文字',
                    position: {
                        top: 10,
                        left: 50
                    }
                }
            ],
            presetAOptions: {
                id: 1,
                fontSize: 50,
                lineHeight: 60,
                color: '000000',
                fontWeight: 'normal',
                letterSpacing: 0,
                textAlign: 'left',
                width: 0,
                height: 0,
                fontFamily: globalFontFamily.Regular,
                content: '链接在此处',
                htmlContent: '链接在此处',
                position: {
                    top: 10,
                    left: 50
                },
                href: '#',
                target: '_blank',
                borderColor: '',
                borderRadiusPercent: 0,
                borderRadiusVW: 0
            },
            presetVideoOptions: {
                id: 1,
                width: 50,
                height: 50,
                position: {
                    top: 10,
                    left: 50
                },
                src: 'https://www.runoob.com/try/demo_source/movie.mp4',
                type: 'video/mp4',
                center: false,
                autoplay: true,
                loop: true,
                muted: true,
                controls: true,
                playsinline: true
            },
            currentPresetOptionId: 1,
            contentTemplate: {
                helper: {
                    helperFold: false,
                    currentIndex: {
                        p: -1,
                        a: -1,
                        video: -1
                    }
                },
                view: {
                    p: [],
                    a: [],
                    video: []
                }
            },
            mainContent: [],
            exporting: false,
            htmlCode: '<div></div>',
            downloadURL: '#'
        }
    },
    methods: {
        deepClone: function(obj){
            return JSON.parse(JSON.stringify(obj));
        },
        submitMainOptions: function(){
            if(this.mainOptions.productName == ''){
                alert('产品型号(英文)');
            }
            else {
                this.mainOptions.optionSubmit = true;
                for(let i = 0;i < this.mainOptions.pageNumber;i++){
                    this.mainContent.push(this.deepClone(this.contentTemplate));
                    this.mainContent[i].id = i+1;
                }
            }
        },
        addP: function(block){
            let p = this.deepClone(this.presetPOptions[this.currentPresetOptionId-1]);
            p.position.top += block.view.p.length+1;
            block.view.p.push(p);
        },
        getPStyle: function(paragraph){
            let style = `
                font-size:${this.px2vw(paragraph.fontSize)};
                line-height:${this.px2vw(paragraph.lineHeight)};
                color:#${paragraph.color};
                top:${paragraph.position.top}vw;
                z-index:1;
            `;
            if(paragraph.fontWeight != 'normal'){
                style += `font-weight:${paragraph.fontWeight};`
            }
            if(paragraph.letterSpacing != 0){
                style += `letter-spacing:${paragraph.letterSpacing}px;`
            }
            if(paragraph.textAlign === 'centerScreen'){
                style += `
                    width:100%;
                    left:0;
                    text-align:center;
                `
            }
            else if(paragraph.textAlign === 'justify'){
                style += `
                    width:${paragraph.width}vw;
                    left:${paragraph.position.left}vw;
                    text-align:${paragraph.textAlign};
                `
            }
            else{
                style += `
                    left:${paragraph.position.left}vw;
                    text-align:${paragraph.textAlign};
                `
            }
            return style;
        },
        addA: function(block){
            let a = this.deepClone(this.presetAOptions);
            a.position.top += block.view.a.length+1;
            block.view.a.push(a);
        },
        getAStyle: function(link){
            let style = `
                font-size:${this.px2vw(link.fontSize)};
                line-height:${this.px2vw(link.lineHeight)};
                color:#${link.color};
                top:${link.position.top}vw;
                z-index:1;
            `;
            if(link.fontWeight != 'normal'){
                style += `font-weight:${link.fontWeight};`
            }
            if(link.letterSpacing != 0){
                style += `letter-spacing:${this.px2vw(link.letterSpacing)};`
            }
            if(link.borderRadiusVW > 0){
                style += `border-radius:${link.borderRadiusVW}vw;`;
            }
            else if(link.borderRadiusPercent > 0){
                style += `border-radius:${link.borderRadiusPercent}%;`;
            }
            if(link.textAlign === 'centerScreen'){
                style += `
                    width:100%;
                    left:0;
                    text-align:center;
                `;
            }
            else if(link.textAlign === 'justify'){
                style += `
                    width:${link.width}%;
                    left:${link.position.left}vw;
                    text-align:${link.textAlign};
                `;
            }
            else{
                style += `
                    left:${link.position.left}vw;
                    text-align:${link.textAlign};
                `;
                if(link.width > 0){
                    style += `width:${link.width}vw;`;
                }
            }
            if(link.borderColor != ''){
                style += `border:1px solid #${link.borderColor};`;
            }
            if(link.height > 0){
                style += `height:${link.height}vw;`;
            }
            return style;
        },
        addVideo: function(block){
            let video = this.deepClone(this.presetVideoOptions);
            video.position.top += block.view.video.length+1;
            block.view.video.push(video);
        },
        getVideoStyle: function(video){
            let style = `
                width:${video.width}vw;
                top:${video.position.top}vw;
                z-index:1;
            `;
            if(video.center){
                style += `
                    left:50%;
                    transform: translateX(-50%);
                `;
            }
            else{
                style += `left:${video.position.left}vw;`;
            }
            return style;
        },
        tagMove: function (block, tagIndex, tag, event) {
            for (let key in block.helper.currentIndex) {
                block.helper.currentIndex[key] = -1;
            }
            block.helper.currentIndex[tag] = tagIndex;
            this.dragStorePosition = {
                top: event.pageY,
                left: event.pageX
            };
            console.log('start', event, event.pageY, event.pageX);
        },
        tagMoveEnd: function (viewElement, block, tag, event) {
            let windowWidth = Math.max(window.innerWidth, 1200);
            viewElement.position.top = (parseFloat(viewElement.position.top) + parseFloat((event.pageY - this.dragStorePosition.top) * 100 / windowWidth)).toFixed(2);
            viewElement.position.left = (parseFloat(viewElement.position.left) + parseFloat((event.pageX - this.dragStorePosition.left) * 100 / windowWidth)).toFixed(2);
            console.log('end', event, viewElement.position, event.pageY, event.pageX, ((event.pageY - this.dragStorePosition.top) * 100 / windowWidth).toFixed(2), ((event.pageX - this.dragStorePosition.left) * 100 / windowWidth).toFixed(2));

            this.helperPositionFocus(block, tag);
        },
        helperPositionFocus: function (block,tag) {
            let tagUpper = tag;
            tagUpper = tagUpper.trim().toLowerCase().replace(tagUpper[0], tagUpper[0].toUpperCase());
            this.$refs.helper[block.id - 1].querySelector('.position' + tagUpper).focus();
        },
        getClass: function(item){
            let myClass = 'font';
            for(let key in globalFontFamily){
                if(item.fontFamily === globalFontFamily[key]){
                    myClass += key;
                }
            }
            return myClass;
        },
        deleteCurrent: function(block,tagIndex,tag){
            let viewTag = [];
            for(let i = 0;i < block.view[tag].length;i++){
                if(tagIndex > i){
                    viewTag.push(block.view[tag][i]);
                }
                else if(tagIndex < i){
                    block.view[tag][i].id--;
                    viewTag.push(block.view[tag][i]);
                }
            }
            block.view[tag] = viewTag;
            for(let key in block.helper.currentIndex){
                block.helper.currentIndex[key] = -1;
            }
        },
        removeAll: function(block,tag){
            block.view[tag] = [];
            for(let key in block.helper.currentIndex){
                block.helper.currentIndex[key] = -1;
            }
        },
        px2vw: function(px){
            return (px*100/this.mainOptions.UIWidth).toFixed(4)+'vw';
        },
        addGlobalColor: function(color){
            if(!this.globalColor.includes(color)){
                this.globalColor.push(color);
            }
        },
        updateHTMLContent: function(item){
            item.htmlContent = item.content.replace(/ /g, "&nbsp;").replace(/\n/g, '<font style="font-family: Arial"><br /></font>');
        },
        changePosition: function(e,item){
            if(e.keyCode == keyCode.a){
				if(item.position.left>=10){
					item.position.left -= 10;
				}
			}
			if(e.keyCode == keyCode.w){
				if(item.position.top>=10){
					item.position.top -= 10;
				}
			}
			if(e.keyCode == keyCode.d){
				if(item.position.left<=90){
					item.position.left -= -10;
				}
			}
			if(e.keyCode == keyCode.s){
				if(item.position.top<=90){
					item.position.top -= -10;
				}
			}

			if(e.keyCode == keyCode.f){
				if(item.position.left>=1){
					item.position.left -= 1;
				}
			}
			if(e.keyCode == keyCode.t){
				if(item.position.top>=1){
					item.position.top -= 1;
				}
			}
			if(e.keyCode == keyCode.h){
				if(item.position.left<=99){
					item.position.left -= -1;
				}
			}
			if(e.keyCode == keyCode.g){
				if(item.position.top<=99){
					item.position.top -= -1;
				}
			}

			if(e.keyCode == keyCode.j){
				if(item.position.left>=0.1){
					item.position.left -= 0.1;
				}
			}
			if(e.keyCode == keyCode.i){
				if(item.position.top>=0.1){
					item.position.top -= 0.1;
				}
			}
			if(e.keyCode == keyCode.l){
				if(item.position.left<=99.9){
					item.position.left -= -0.1;
				}
			}
			if(e.keyCode == keyCode.k){
				if(item.position.top<=99.9){
					item.position.top -= -0.1;
				}
			}

			if(e.keyCode == keyCode.left){
				if(item.position.left>=0.01){
					item.position.left -= 0.01;
				}
			}
			if(e.keyCode == keyCode.up){
				if(item.position.top>=0.01){
					item.position.top -= 0.01;
				}
			}
			if(e.keyCode == keyCode.right){
				if(item.position.left<=99.99){
					item.position.left -= -0.01;
				}
			}
			if(e.keyCode == keyCode.down){
				if(item.position.top<=99.99){
					item.position.top -= -0.01;
				}
            }
            
            e.target.value = '';
        },
        exportHTML: function(){
            this.exporting = true;
            this.htmlCode = this.$refs.html.outerHTML;
            this.$nextTick(()=>{
                window.scrollTo(0,0);
            });
        },
        returnExport: function(){
            this.exporting = false;
        },
        download: function(){
            let html = `
                <!DOCTYPE html>
                <html>
                
                <head>
                    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                    <title>${this.mainOptions.productName}</title>
                </head>

                <body style="padding:0;margin:0;">
                    {{bodyContent}}
                </body>

                </html>
            `;
            let bodyContent = this.$refs.output.outerHTML.replace(/&quot;/g,'\'')
            .replace(/autoplay=\"autoplay\"/g, 'autoplay')
                .replace(/autoplay=\"\"/g, 'autoplay')
                .replace(/loop=\"loop\"/g, 'loop')
                .replace(/loop=\"\"/g, 'loop')
                .replace(/controls=\"controls\"/g, 'controls')
                .replace(/controls=\"\"/g, 'controls')
                .replace(/data-muted=\"true\"/g, 'muted')
                .replace(/muted=\"true\"/g, 'muted')
                .replace(/muted=\"\"/g, 'muted')
                .replace(/playsinline=\"true\"/g, 'playsinline')
                .replace(/playsinline=\"\"/g, 'playsinline');
            html = html.replace('{{bodyContent}}',bodyContent);
            
            console.log(html)

            let blob = new Blob([html], {type: 'text/html'});
            this.downloadURL = URL.createObjectURL(blob);

            this.$nextTick(()=>{
                document.getElementById('blob').click();
            });
        }
    },
    computed: {
        getGlobalStyle: function(){
            let style = `
                #${this.mainOptions.productName}-main .block{
                    width:100%;
                    position:relative;
                }
                #${this.mainOptions.productName}-main .block img{
                    width:100%;
                    display:block;
                }
            `;
            
            let family = new Set();
            let fontFace = '';
            let pWordFamily = [];
            let aWordFamily = [];
            let videoFlag = false;
            for(let i = 0;i < this.mainContent.length;i++){
                for(let j = 0;j < this.mainContent[i].view.p.length;j++){
                    for(let key in globalFontFamily){
                        if(this.mainContent[i].view.p[j].fontFamily === globalFontFamily[key] && (!pWordFamily.includes(key))){
                            pWordFamily.push(key);
                        }
                    }
                }
                for(let j = 0;j < this.mainContent[i].view.a.length;j++){
                    for(let key in globalFontFamily){
                        if(this.mainContent[i].view.a[j].fontFamily === globalFontFamily[key] && (!aWordFamily.includes(key))){
                            aWordFamily.push(key);
                        }
                    }
                }
                if(this.mainContent[i].view.video.length > 0){
                    videoFlag = true;
                }
            }
            family = new Set(pWordFamily.concat(aWordFamily));
            // console.log(family,pWordFamily,aWordFamily)
            for(let value of family){
                fontFace += globalFontFace[value];
                fontFace += `
                    #${this.mainOptions.productName}-main .block .font${value} {
                        font-family:${globalFontFamily[value]}
                    }
                `;
            }

            if(pWordFamily.length > 0){
                style += `
                    #${this.mainOptions.productName}-main .block p {
                        white-space: nowrap;
                        margin: 0;
                        position: absolute;
                    }
                `;
            }
            if(aWordFamily.length > 0){
                style += `
                    #${this.mainOptions.productName}-main .block a {
                        white-space: nowrap;
                        margin: 0;
                        position: absolute;
                        display: block;
                        text-decoration: none;
                    }
                `;
            }

            if(this.mainOptions.minWidth > 0){
                style += `
                    @media screen and (max-width: ${this.mainOptions.minWidth}px) {
                        #${this.mainOptions.productName}-main .block{
                            width:100vw;
                        }
                        #${this.mainOptions.productName}-main .block .image{
                            width:100vw;
                        }
                    }
                `;
            }

            if(videoFlag){
                style += `
                    #${this.mainOptions.productName}-main .block video {
                        position: absolute;
                        display: block;
                    }
                `;
            }

            style += fontFace;
            return style;
        },
        getGlobalColor: function(){
            let colorString = '';
            this.globalColor.map((value,index)=>{
                colorString += value + '/';
            });
            return colorString.slice(0,colorString.length-1);
        }
    },
    mounted() {
        
    }
});